<template>
<div class='knowledge-list'>
  <div class="pageLevel" v-if="!sub">
    <!--  搜索    -->
    <div>
      <el-form label-width="100px" class="demo-ruleForm">
        <el-row>
          <el-col :span='6'>
            <el-form-item label="状态：">
              <el-radio-group v-model="searchData.state" size="small" @change='radioChange'>
                <el-radio-button v-for='(item, index) in statusList' :label="index" :key='index'>{{item}}</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span='6'>
            <el-form-item label="知识分类:">
              <el-select v-model="searchData.knowledgeTypeId" size="small" style='width: 100%'>
                <el-option value='' label='全部' ></el-option>
                <el-option v-for="item in knowledgeTypeList" :key="item.id" :value="item.id" :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='4'>
            <el-form-item label="类型:">
              <el-select v-model="searchData.postType" size="small"  style='width: 100%'>
                <el-option label='全部' :value='null'></el-option>
                <el-option v-for="(item, index) in postTypeList" :key="index" :value="index" :label="item"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='6'>
            <el-form-item label="标题搜索:">
              <el-input class="input" v-model="searchData.title" size="small" placeholder="请输入知识标题"
                        @keyup.enter.native='getTableData(pageSize, 1)' style='width: 257px' maxlength = '32' clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span='6'>
            <el-form-item label='应用端:'>
               <div class='radio-checkbox'>
                 <el-radio :label='0' v-model='searchData.applyCode[0]' @change='handleApplyCode'>全部</el-radio>
                 <el-checkbox-group v-model="searchData.applyCode" >
                   <el-checkbox v-for='(item, index) in applyList' :label="index+1" :key='index'>{{item}}</el-checkbox>
                 </el-checkbox-group>
               </div>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='阅读对象:' v-if='searchData.applyCode[0] == 0 || searchData.applyCode.indexOf(2) > 0'>
              <div class='radio-checkbox'>
                <el-radio :label='0' v-model='searchData.readersCode[0]' @change='handleReadersCode'>全部</el-radio>
                <el-checkbox-group v-model="searchData.readersCode" v-if='searchData.applyCode.indexOf(2) > 0'>
                  <el-checkbox v-for='(item, index) in readersList' v-if='item.typeId != "3333333333"' :label="item.typeId" :key="index">{{item.name}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span='8'>
            <el-form-item label-width='20px'>
              <el-button type="primary" size="small" @click="getTableData(pageSize, 1)">查 询</el-button>
              <el-button size="small" @click="routerPush('new')" type="primary" class="addDetail" v-if='setRole("新增")'>新增知识</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--表格-->
    <div class='table-data'>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
        <el-table-column prop="title" label="标题" align="center"></el-table-column>
        <el-table-column prop="knowledgeTypeName" label="知识分类" align="center"></el-table-column>
        <el-table-column prop="postType" label="类型" align="center">
          <template slot-scope='scope'>{{postTypeList[scope.row.postType]}}</template>
        </el-table-column>
        <el-table-column prop="applyCode" label="应用端" :formatter='dealApply' align="center"></el-table-column>
        <el-table-column prop="readersCode" label="阅读对象" :formatter='dealreaders' align="center"></el-table-column>
        <el-table-column v-if='searchData.state == 0 || searchData.state == 2' prop="updateTime" :formatter='dealDate' label="上架时间" align="center"></el-table-column>
        <el-table-column v-if='searchData.state == 0' prop="weight" label="权重值" align="center"></el-table-column>
        <el-table-column v-if='searchData.state == 1'prop="updateTime" label="更新时间" :formatter='dealDate' align="center"></el-table-column>
        <el-table-column v-if='searchData.state == 2' prop="lowerTime" label="下架时间" :formatter='dealDate' align="center"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="small" @click="routerPush('edit', scope.row.id)" type="text" class="addDetail" v-if='setRole("编辑")'>编辑</el-button>
            <template v-if='scope.row.state == 0'>
              <el-button size="small" @click="openDialog(1, scope.row.id)" type="text" class="addDetail" v-if='setRole("下架")'>下架</el-button>
              <el-button size="small" @click="openDialog(2, scope.row.id, scope.row.weight)" type="text" class="addDetail" v-if='setRole("修改权重")'>修改权重</el-button>
            </template>
            <template v-if='scope.row.state == 1 || scope.row.state == 2'>
              <el-button size="small" @click="openDialog(3, scope.row.id)" type="text" class="addDetail" v-if='setRole("删除")'>删除</el-button>
            </template>
          </template>
          <template>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pageblock">
      <el-button size="small" type="primary" class="topage" @click="getTableData(pageSize, pageNum)">跳转</el-button>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum" :page-sizes="[5,20,30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </div>
    <!-----------弹框-------------------------->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :show-close='false'>
      <el-form  label-width='80px' :model='dialogValue' :rules='ruleDialogValue' class="demo-ruleForm" ref="ratingPriority">
        <h3 v-if='dialogType == 1' class='offline-tips'>确定要将该条知识下架吗?</h3>
        <h3 v-else-if='dialogType == 3' class='offline-tips'>确定要删除该条知识吗?</h3>
        <template v-else-if='dialogType == 2'>
          <el-form-item  label='设置权重' prop='priority'>
            <el-input style='width: 200px' v-model='dialogValue.priority' maxlength='5'
                      @keyup.native='replace(dialogValue, "priority")' clearable></el-input>
          </el-form-item>
          <el-form-item label=''>
            <p class='tips'>*权重值越大，排序越靠前，权重值为正整数，<br/>可输入范围：0—10000</p>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
            <el-button @click="cancel()">取消</el-button>
            <el-button type="primary" @click="confirmDialog">确定</el-button>
          </div>
    </el-dialog>
  </div>

  <div class="pageLevel" v-else>
    <router-view></router-view>
  </div>
</div>
</template>

<script>
  import {mapState} from 'vuex'
  import util from '@/util'
  import {
    findEmployeeTypeList,
    findKnowledgeListPage,
    shelvesKnowledge,
    updateWeight,
    deleteKnowledge,
    findKnowledgeClassificationListPage
  } from '@/api'
  export default {
    name: 'knowledge-list',
    data () {
      const checkPriorityRating = (rule, value, callback) => {
        if (+value > 10000) {
          return callback(new Error('超过输入范围'));
        } else {
          callback();
        }
      };
      return {
        total: 0,
        statusList: ['已上架', '已保存', '已下架'],
        postTypeList: ['图文','音频'], //内容种类列表
        applyList: ['老板端', '员工端'],
        readersList: [], //阅读对象
        knowledgeTypeList: [], //知识分类
        dialogVisible: false, // 弹框
        dialogTitle: '',
        pageSize: 20,
        pageNum: 1,
        tableData: [],
        searchData: {
          state: 0, //状态（0：已上架，1：已保存，2：已下架）
          knowledgeTypeId: '',
          postType: null, //（0：图文，1音频）
          title: '',
          applyCode: [0],
          readersCode: [0],
        },
        dialogType: null, // 1 下架弹框  2 权重弹框
        currentItem: null, //当前操作知识id
        dialogValue: {
          priority: null, //  权重
        },
        ruleDialogValue: {
          priority: [{required: true, message: '请输入权重', trigger: 'blur'},
            {validator: checkPriorityRating, trigger: 'blur'}], //权重校验
        }
      }
    },
    watch: {
      'searchData.applyCode': {
        handler: function(cur, old) {
          if (cur.length > 1) {
            cur[0] = null
          } else {
            cur[0] = 0
          }
        },
      },
      'searchData.readersCode': {
        handler: function(cur, old) {
          if (cur.length > 1) {
            cur[0] = null
          } else {
            cur[0] = 0
          }
        },
      },
      sub: {
        handler: function(val, oldVal){
          if (oldVal != null && val == false) {
            this.getTableData(this.pageSize, 1)
          }
        },
        deep: true
      },
      isReLoadData: function(val) {
        if (val == true) {
          let status = +util.getQuery('status')
          if(!status && status != 0) {
            this.searchData.status = null
          }else {
            this.$set(this.searchData, 'state', status)
          }
          this.getTableData(this.pageSize, this.pageNum)
          this.$store.commit("SET_ISRELOADDATA", false);
        }
      },
    },
    computed: mapState([
      "sub",
      "power",
      "merchantId",
      "isReLoadData"
    ]),
    created () {},
    mounted () {
      let status = +util.getQuery('status')
      if (status) {
        this.$set(this.searchData, 'state', status)
      }
      if(this.sub == false){
        this.findEmployeeList()
        this.getKnowledgeType()
        this.getTableData(this.pageSize, this.pageNum)
      }
    },
    methods: {
      //知识分类列表
      getKnowledgeType () {
        let data = {
          shopId: this.merchantId,
          name: '',
          pageNum: 1,
          pageSize: 10000,
          state: 0
        }
        findKnowledgeClassificationListPage(data).then(res => {
          if (res.code == 200) {
            this.knowledgeTypeList = res.data.list
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      //获取员工列表
      findEmployeeList() {
        let data = {
          pageSize: 20,
          pageNum: 1,
        }
        findEmployeeTypeList(data).then(res => {
          if (res.code == 200) {
            this.readersList = res.data.list
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      //获取列表数据
      getTableData (pageSize, pageNum) {
        let data = JSON.parse(JSON.stringify(this.searchData))
        data.shopId = this.merchantId
        data.pageNum = pageNum
        data.pageSize = pageSize
        if (data.readersCode[0] != 0) {
          data.readersCode.splice(0, 1)
          // data.readersCode = data.readersCode.join(',')
        } else {
          data.readersCode = null
        }
        if (data.applyCode[0] != 0) {
          data.applyCode.splice(0,1)
          data.applyCode = data.applyCode.join(',')
        } else {
          data.applyCode = ''
        }

        findKnowledgeListPage(data).then(res => {
          if (res.code == 200) {
            this.tableData = res.data.list
            this.total = res.data.pageTotal
          } else {
            this.$message.error(res.msg)
          }
        })
      },
      // 下架 or 修改权重 or 删除
      confirmDialog() {
        let that = this
        switch (this.dialogType) {
          //下架
          case 1:
            shelvesKnowledge({
              id: that.currentItem,
              state: 2
            }).then(res =>{
              if(res.code == 200){
                this.getTableData(this.pageSize, 1)
                this.$message.success('下架成功')
                this.cancel()
              } else {
                this.$message.error(res.msg)
              }
            })
            break;
          //修改权重
          case  2:
            this.$refs.ratingPriority.validate((valid) => {
              if (valid) {
                updateWeight({
                  id: that.currentItem,
                  weight: that.dialogValue.priority
                }).then(res =>{
                  if(res.code == 200){
                    this.getTableData(this.pageSize, 1)
                    this.$message.success('设置成功')
                    this.cancel();
                  }else {
                    this.$message.error(res.msg)
                  }
                })
              }
            })
            break;
            //删除知识
          case 3:
            deleteKnowledge({
              id: that.currentItem
            }).then(res =>{
              if(res.code == 200){
                this.getTableData(this.pageSize, 1)
                this.$message.success('删除成功')
                this.cancel()
              }else {
                this.$message.error(res.msg)
              }
            })
            break;
        }
      },
      //选择状态
      radioChange(val) {
        this.getTableData(this.pageSize, this.pageNum)
      },
      //打开弹框
      openDialog(type, id, weight = '') {
        this.currentItem = id
        switch (type) {
          case 1:
            this.dialogTitle = '知识下架'
            break;
          case 2:
            this.dialogTitle = '权重修改'
            this.dialogValue.priority = weight
            break;
          case 3:
            this.dialogTitle = '删除确认'
            break;
        }
        this.dialogType = type
        this.dialogVisible = true
      },
      //取消下架或者修改权重
      cancel() {
        this.dialogVisible = false
        this.dialogType = null
        this.currentItem = null
        if(this.dialogType == 2){    //修改权重
          this.dialogValue.priority = null
          this.$refs.ratingPriority.clearValidate()
        }
      },
      //选择应用对象
      handleApplyCode (val) {
        if (val == null) {
          this.$set(this.searchData, 'applyCode', [0])
          this.searchData.readersCode = [0]
        }
      },
      handleReadersCode(val) {
        if (val == null) {
          this.$set(this.searchData, 'readersCode', [0])
        }
      },
      //应用端数据处理
      dealApply (row, column, cellValue) {
        let arr = []
        if (cellValue.indexOf(',') != -1) {
          arr = cellValue.split(',')
        } else {
          arr = new Array(cellValue)
        }
        return arr.map((v) => {
          return this.applyList[v-1]
        }).join('、')
      },
      //阅读对象处理
      dealreaders (row, column, cellValue) {
        let arr = []
        if (cellValue.indexOf(',') != -1) {
          arr = cellValue.split(',')
        } else {
          arr = new Array(cellValue)
        }
        return arr.map((v) => {
          for (let i=0;i<this.readersList.length;i++) {
            if (v === this.readersList[i].typeId) {
              return this.readersList[i].name
            }
          }
        }).join('、')
      },
      //时间处理
      dealDate (row, column, cellValue) {
        if (!cellValue) {
          return ''
        }
        let date = util.forDateAndTime(cellValue)
        let arr = date.split(' ')
        let arr2 = arr[1].split(':')
        return `${arr[0]} ${arr2[0]}:${arr2[1]}`
      },
      //路由跳转详情页
      routerPush (handle, targetId = '') {
        util.routerTo('/operate-management/knowledge-base/knowledge-list/knowledge-details',{
          handle: handle,
          targetId: targetId,
        })
      },
      // 更改每页条数
      handleSizeChange(val) {
        this.pageSize = val;
        this.getTableData(val, this.pageNum);
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.getTableData(this.pageSize, val);
      },
      //配置权限
      setRole(key) {
        return util.selectTitle(this.power, key);
      },
      //字符串过滤
      replace (obj, key) {
        let that = this
        let event = event || window.event
        if (event.keyCode == 13) {
          setTimeout(() => {
            that.validItem(obj, key)
          }, 100)
        } else {
          that.validItem(obj, key)
        }
      },
      validItem (obj, key) {
        let res = ''
        switch (key) {
          case 'priority':
            res = util.replaceNumber(obj[key])
            if (parseInt(res) === 0) {
              res = 0
            }
            break
        }
        this.$set(obj, key, res)
      },
    }
  }
</script>

<style scoped lang='less'>
.knowledge-list {
  position: absolute;
  top: 70px;
  left: 11px;
  right: 11px;
  bottom: 10px;
  .tips {
    color: darkgray;
    line-height: 20px;
  }
  .radio-checkbox {
      display: flex;
      justify-content: flex-start;
    .el-radio, .el-radio__input {
      line-height: 40px;
    }
  }
  .offline-tips {
    text-align: center;
    padding: 20px 0;

  }
}
.dialog-footer {
  text-align: center;
}
</style>
